﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using CE.Configuration;
using CE.Global;
using CE.User;
using CE.Image;
using CE.CarInsurance;
using CE.Mail;
using CE.Company;

public partial class car_insurance_your_details : MyLanguageAndSessionBasePage
{
    CE.User.Profile _profile = null;
    CE.User.ProfileDB _profiledb = null;
    Contact _contact = null;
    ContactDB _contactdb = null;
    string _redirectUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.YourDetailsTitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.YourDetailsKeyword;

        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.YourDetailsDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);

        if (Session[CE.Global.General.UserId] == null)
        {
            divExisting.Visible = true;
        }
        else
        {
            divExisting.Visible = false;
            checkIsAgreement.Visible = false;
            lblCreateAccount.Visible = false;
        }

        if (Session[General.CarPolicyId] != null && Session[General.IsCarRestoreResult] != null)
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/quote-results.aspx", Page);
            Response.Redirect(_redirectUrl);
        }

        if (!IsPostBack)
        {
            HtmlControl htmlClass = (HtmlControl)Master.FindControl("cls1");
            htmlClass.Attributes.Add("class", "selected");

            Session["UMMSG"] = null;
            if (Session[General.UserId] != null)
            {
                if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Provider))
                {
                    btnBack.Visible = true;
                    //btnUpdateCarProfile.Visible = false;
                }
                else
                {
                    btnBack.Visible = true;
                    //btnUpdateCarProfile.Visible = false;
                }
            }
            else
            {
                //btnUpdateCarProfile.Visible = false;
                btnBack.Visible = true;
            }

            //lblSortBy.Text = "0";
            if (Request.Params["sortby"] != null)
            {
                //lblSortBy.Text = Request.Params["sortby"].ToString();
            }

            HyperLink _lnkTest = new HyperLink();

            //btnUpdateCarProfile.Attributes.Add("onmouseover", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.SaveCloseButtonHoverImageUrl) + "';");
            //btnUpdateCarProfile.Attributes.Add("onmouseout", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.SaveCloseButtonImageUrl) + "';");
            btnNext.Attributes.Add("onmouseover", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.NextButtonHoverImageUrl) + "';");
            btnNext.Attributes.Add("onmouseout", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.NextButtonImageUrl) + "';");
            btnBack.Attributes.Add("onmouseover", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.BackButtonHoverImageUrl) + "';");
            btnBack.Attributes.Add("onmouseout", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.BackButtonImageUrl) + "';");

            _lnkTest = null;

            usrDOB.StartYear = General.GetUTCDateTime().Year - 75;
            usrDOB.EndYear = General.GetUTCDateTime().Year - 18;


            txtEmailAddress.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmailAddress.ClientID + "','" + rfvEmail.ClientID + "','" + rfvEmailValid.ClientID + "');");
            txtConfirmEmailAddress.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtConfirmEmailAddress.ClientID + "','" + rfvConfirmEmail.ClientID + "','" + rfvConfirmEmailValid.ClientID + "');");
            txtSurName.Attributes.Add("onblur", "ShowValidationEffect('" + txtSurName.ClientID + "','" + rfvSurName.ClientID + "');");
            //ddlYearDriveSg.Attributes.Add("onblur", "ShowValidationEffect('" + ddlYearDriveSg.ClientID + "','" + rfvYearDriveSg.ClientID + "');");

            Int64 _userId = 0;
            if (Session[General.UserId] == null && Session[General.CarId] != null && Session[CE.Global.General.UserProfileAndContactComplete] != null)
            {
                //btnUpdateCarProfile.Visible = false;
                ShowCustomerDetailByCar(Convert.ToInt64(Session[General.CarId].ToString()));
            }
            else if (Session[General.UserId] != null)
            {

                _userId = Convert.ToInt64(Session[General.UserId].ToString());
                if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Customer))
                {
                    ShowCustomerDetail(_userId);
                    //btnUpdateCarProfile.Visible = false;
                }
                else if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Provider))
                {
                    ShowCustomerDetail(_userId);
                }
            }

            //hplProfile.NavigateUrl = "";
            //hplCarResults.Attributes.Clear();
            //hplCarResults.NavigateUrl = "";

            Page.Form.DefaultButton = btnNext.UniqueID;
            LogUserViewedHistory();

            GetCarPolicyDetail();
        }
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //Salutation
        //ddlSalutation.ChangeValidationEffectServerSide(strValidationGroup);

        //First Name
        if (revFirstName.Enabled && revFirstName.ValidationGroup == strValidationGroup)
        {
            revFirstName.Validate();
            if (revFirstName.IsValid == false)
            {
                txtFirstName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtFirstName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtFirstName.ControlStyle.CssClass = "";
        }


        //Surname
        if (rfvSurName.Enabled && rfvSurName.ValidationGroup == strValidationGroup)
        {
            rfvSurName.Validate();
            if (rfvSurName.IsValid == false)
            {
                txtSurName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtSurName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtSurName.ControlStyle.CssClass = "";
        }

        if (revSurname.Enabled && revFirstName.ValidationGroup == strValidationGroup)
        {
            revSurname.Validate();
            if (revSurname.IsValid == false)
            {
                txtSurName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtSurName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtSurName.ControlStyle.CssClass = "";
        }
        //Mobile No
        txtMobileNo.ChangeValidationEffectServerSide(strValidationGroup);
        //Date of birth
        usrDOB.ChangeValidationEffectServerSide(strValidationGroup);

        //Occupation
        ddlOccupation.ChangeValidationEffectServerSide(strValidationGroup);

        

        if (cvConfirmEmail.Enabled && cvConfirmEmail.ValidationGroup == strValidationGroup && txtConfirmEmailAddress.Visible)
        {
            cvConfirmEmail.Validate();
            if (cvConfirmEmail.IsValid == false)
            {
                txtConfirmEmailAddress.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtConfirmEmailAddress.ControlStyle.CssClass = "";
            }

        }
        else
        {
            txtConfirmEmailAddress.ControlStyle.CssClass = "";
        }

        //Job Nature
        //ddlJobNature.ChangeValidationEffectServerSide(strValidationGroup);
        //Marital Status
        //ddlMaritalStatus.ChangeValidationEffectServerSide(strValidationGroup);
        //Type Of Indentification
        /***********************************************************************Comment on 13/05/2010
        ddlIDType.ChangeValidationEffectServerSide(strValidationGroup);
        //ID Number
        txtIdNumber.ChangeValidationEffectServerSide(strValidationGroup);

        //ID Prefix & ID Type
        if (csvIdTypePrefix.Enabled && csvIdTypePrefix.ValidationGroup == strValidationGroup)
        {
            if (ddlIDType.IsValidRequirement() && txtIdNumber.IsValidePrefixRequirement())
            {
                csvIdTypePrefix.Validate();
                if (csvIdTypePrefix.IsValid == false)
                {
                    ddlIDType.ChangeValidateEffect(true);
                    txtIdNumber.ChangeValidateEffectPrefix(true);
                    csvIdTypePrefix.ErrorMessage = "Identification type and NRIC/FIN number's prefix character are not matched.";
                }
                else
                {
                    ddlIDType.ChangeValidateEffect(false);
                    txtIdNumber.ChangeValidateEffectPrefix(false);
                }
            }
        }
        else
        {
            ddlIDType.ChangeValidateEffect(false);
            //txtIdNumber.ChangeValidateEffectPrefix(false);
        }*/

        //Year of Driving In SG
        #region"Year of Driving"

        //if (rfvYearDriveSg.Enabled && rfvYearDriveSg.ValidationGroup == strValidationGroup)
        //{
        //    rfvYearDriveSg.Validate();
        //    if (rfvYearDriveSg.IsValid == false)
        //    {
        //        ddlYearDriveSg.ControlStyle.CssClass = "validationError";
        //    }
        //    else
        //    {
        //        ddlYearDriveSg.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    ddlYearDriveSg.ControlStyle.CssClass = "";
        //}

        //if (csvAgeAndYear.Enabled && csvAgeAndYear.ValidationGroup == strValidationGroup)
        //{
        //    csvAgeAndYear.Validate();
        //    if (csvAgeAndYear.IsValid == false)
        //    {
        //        ddlYearDriveSg.ControlStyle.CssClass = "validationError";
        //        usrDOB.ChangeValidationEffect();
        //    }
        //    else
        //    {
        //        ddlYearDriveSg.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    ddlYearDriveSg.ControlStyle.CssClass = "";
        //}
        #endregion
        /***********************************************************************Comment on 13/05/2010
        //Nationality
        ddlNationality.ChangeValidationEffectServerSide(strValidationGroup);

        //Mobile Number
        txtMobileNo.ChangeValidationEffectServerSide(strValidationGroup); */

        //if (txtPassword.Text != txtReEnterPassword.Text)
        //{
        //    txtPassword.Text = string.Empty;
        //    txtReEnterPassword.Text = string.Empty;

        //    txtPassword.ControlStyle.CssClass = "validationError";
        //    txtReEnterPassword.ControlStyle.CssClass = "validationError";
        //}
        //else
        //{
        //    txtPassword.ControlStyle.CssClass = "";
        //    txtReEnterPassword.ControlStyle.CssClass = "";
        //}

        //if (rfvPassword.Enabled && rfvPassword.ValidationGroup == strValidationGroup)
        //{
        //    rfvPassword.Validate();
        //    if (rfvPassword.IsValid == false)
        //    {
        //        txtPassword.ControlStyle.CssClass = "validationError";
        //    }
        //    else
        //    {
        //        txtPassword.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    txtPassword.ControlStyle.CssClass = "";
        //}

        //if (rfvReEnterPassword.Enabled && rfvReEnterPassword.ValidationGroup == strValidationGroup)
        //{
        //    rfvReEnterPassword.Validate();
        //    if (rfvReEnterPassword.IsValid == false)
        //    {
        //        txtReEnterPassword.ControlStyle.CssClass = "validationError";
        //    }
        //    else
        //    {
        //        txtReEnterPassword.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    txtReEnterPassword.ControlStyle.CssClass = "";
        //}

        //if (txtPassword.Text.Length < 6 || txtReEnterPassword.Text.Length < 6)
        //{
        //    txtPassword.ControlStyle.CssClass = "validationError";
        //    txtReEnterPassword.ControlStyle.CssClass = "validationError";
        //}
        //else
        //{
        //    if (txtPassword.Text == txtReEnterPassword.Text)
        //    {
        //        txtPassword.ControlStyle.CssClass = "";
        //        txtReEnterPassword.ControlStyle.CssClass = "";
        //    }
        //    else
        //    {
        //        txtPassword.ControlStyle.CssClass = "validationError";
        //        txtReEnterPassword.ControlStyle.CssClass = "validationError";
        //    }
        //}



        //View My Result By Sorting
        //if (rfvSortBy.Enabled && rfvSortBy.ValidationGroup == strValidationGroup)
        //{
        //    rfvSortBy.Validate();
        //    if (rfvSortBy.IsValid == false)
        //    {
        //        ddlSortBy.ControlStyle.CssClass = "validationError";
        //    }
        //    else
        //    {
        //        ddlSortBy.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    ddlSortBy.ControlStyle.CssClass = "";
        //}


    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogViewedHistory("CI", Request, "Car Insurance profile.");
    }

    protected void CheckAgeAndYear(object sender, ServerValidateEventArgs args)
    {
        bool _isValid = true;
        DateTime _dtDOB = usrDOB.GetDate();
        int _expYear = 0;// Convert.ToInt32(ddlYearDriveSg.Text);
        int _age = General.GetUTCDateTime().Year - _dtDOB.Year;

        int _possibleExpYear = _age - 18;

        if (_possibleExpYear < 0)
        {
            _isValid = false;
        }
        else if (_expYear > _possibleExpYear)
        {
            _isValid = false;
        }

        args.IsValid = _isValid;
    }

    private void ShowCustomerDetailByCar(Int64 CarId)
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();

        _cardetail = _cardetaildb.GetCar(CarId, 0);
        if (_cardetail != null)
        {
            if (_cardetail.Info5.Length > 0 &&
                _cardetail.Info6.Length > 0 &&
                _cardetail.Info7.Length > 0 &&
                _cardetail.Info8.Length > 0 &&
                _cardetail.Info9.Length > 0 &&
                _cardetail.Info10.Length > 0 &&
                _cardetail.Info11.Length > 0 &&
                _cardetail.Info12.Length > 0 &&
                _cardetail.Info13.Length > 0 &&
                _cardetail.Info14.Length > 0)
            {
                txtEmailAddress.Text = _cardetail.Info5;
                txtMobileNo.PhoneNo = _cardetail.Info6;
                txtSurName.Text = _cardetail.Info7;
                if (_cardetail.Info8.Length > 0)
                {
                    txtFirstName.Text = _cardetail.Info8;
                }
                ddlGender.Gender = _cardetail.Info9;
                DateTime _dtDOB = Convert.ToDateTime(_cardetail.Info10);
                usrDOB.Year = _dtDOB.Year;
                usrDOB.Month = _dtDOB.Month;
                usrDOB.Day = _dtDOB.Day;

                ddlOccupation.Occupation = _cardetail.Info11;
                //ddlJobNature.JobNature = _cardetail.Info12;
                //ddlMaritalStatus.MaritalStatus = _cardetail.Info13;
                //ddlYearDriveSg.Text = _cardetail.Info14;
                //ddlSalutation.Saluation = _cardetail.Info15;

                SetPassword(false);
            }
            else
            {
                if (Session[General.UserId] != null)
                {
                    ShowCustomerDetail(Convert.ToInt64(Session[General.UserId].ToString()));
                }
            }
        }
    }

    private void ShowCustomerDetail(Int64 UserId)
    {
        _profile = new CE.User.Profile();
        _profiledb = new ProfileDB();
        _contact = new Contact();
        _contactdb = new ContactDB();

        _profile = _profiledb.GetProfile(UserId);
        _profiledb = null;

        if (_profile != null)
        {
            //ddlSalutation.Saluation = _profile.Salutation;
            txtFirstName.Text = _profile.FirstName;
            txtSurName.Text = _profile.SurName;

            //ddlMaritalStatus.MaritalStatus = _profile.MaritalStatus.ToString();
            ddlOccupation.Occupation = _profile.Occupation.ToString();
            //ddlJobNature.JobNature = _profile.JobNature;

            //ddlYearDriveSg.Text = _profile.YearDriveSg.ToString();
            ddlGender.Gender = _profile.Gender.ToString();

            usrDOB.Day = _profile.DOB.Day;
            usrDOB.Month = _profile.DOB.Month;
            usrDOB.Year = _profile.DOB.Year;

            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                txtMobileNo.PhoneNo = _contact.Mobile;
                txtEmailAddress.Text = _contact.Email;
                txtEmailAddress.ReadOnly = true;

                SetPassword(false); //disable
            }

            //Disable DOB, Gender and Year of Driving Exp Sg
            if (Session[CE.Global.General.UserTypeId].ToString() == "400")
            {
                if (Session[General.UserProfileAndContactComplete].ToString() == "1")
                {
                    usrDOB.IsEnabled = false;
                    ddlGender.IsEnabled = false;
                }
            }
            _profile = null;
        }
    }

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();

            _contact = new Contact();
            _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = ""; // ddlSalutation.GetSalutation();
                _profile.FirstName = txtFirstName.Text;
                _profile.SurName = txtSurName.Text;
                _profile.DOB = usrDOB.GetDate();
                _profile.Gender = Convert.ToChar(ddlGender.GetGender());

                _profile.MaritalStatus = -1;// Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
                _profile.JobNature = "";// ddlJobNature.GetJobNature();
                _profile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());
                _profile.YearDriveSg = 0;//Convert.ToInt16(ddlYearDriveSg.Text);
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtMobileNo.GetPhoneNo();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }
                else
                {
                    //divNewErrorMessage.Visible = true;
                    //lblCarInsProfileMessage.Text = "Error found in profile update!";
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[General.UserPhoneNo] = txtMobileNo.GetPhoneNo();
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    }
                }
                else
                {
                    //divNewErrorMessage.Visible = true;
                    //lblCarInsProfileMessage.Text = "Error found in contact update!";
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }

        if (_retValue > 0)
        {
            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(CarId, UserId);

            if (_cardetail != null)
            {
                _cardetail.Info5 = txtEmailAddress.Text;
                _cardetail.Info6 = txtMobileNo.GetPhoneNo();
                _cardetail.Info7 = txtSurName.Text.Trim();
                if (txtFirstName.Text.Trim().Length > 0)
                {
                    _cardetail.Info8 = txtFirstName.Text.Trim();
                }
                //CultureInfo ci = CultureInfo.CurrentCulture;
                _cardetail.Info9 = ddlGender.GetGender();
                _cardetail.Info10 = usrDOB.GetDate().ToString("dd-MMM-yyyy");
                _cardetail.Info11 = ddlOccupation.GetOccupation();
                _cardetail.Info12 = "";// ddlJobNature.GetJobNature();
                _cardetail.Info13 = "";// ddlMaritalStatus.GetMaritalStatus();
                _cardetail.Info14 = "";// ddlYearDriveSg.Text;
                _cardetail.Info15 = "";// ddlSalutation.GetSalutation();
                _cardetail.RefCEUserId = UserId;
            }

            //RefUserId only update
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
            _carpolicy.RefCEUserId = UserId;

            _retValue = _cardetaildb.Insert(_cardetail);

            _retValue = _carpolicydb.Insert(_carpolicy);

            //update RefIds
            CarDetailTHDB cardb = new CarDetailTHDB();
            cardb.UpdateCarDetailPolicy(CarId, UserId);

            if (_retValue <= 0)
            {
                //divNewErrorMessage.Visible = true;
                //lblCarInsProfileMessage.Text = "Error found in car quote profile update";
            }
        }

        return _retValue;
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        ChangeValidationEffectServerSide("carprofile");
        //divNewErrorMessage.Visible = false;
        if (Page.IsValid)
        {
            Int64 _userId = 0;
            Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
            bool _newuser = false;
            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
            }
            else
            {
                _newuser = true;
            }

            if (UpdateProfile(_userId, _carId) > 0)
            {
                //lblSortBy.Text = ddlSortBy.Text;
                if (_newuser)
                {
                    SendMailToUser(txtEmailAddress.Text.Trim(), Session[CE.Global.General.UserName].ToString(), txtMobileNo.GetPhoneNo());
                }
                //Response.Redirect("~/quote-results.aspx?sortby=" + lblSortBy.Text);
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/quote-results.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/car-details.aspx", Page);
        Response.Redirect(_redirectUrl);
    }

    protected void btnNewImage_Click(object sender, EventArgs e)
    {
        //CreateUpdateImageAndSession();
    }

    private void CreateUpdateImageAndSession()
    {
        //MyImage myimage = new MyImage();
        //string salt = "";

        //if (Session[CE.Global.General.SecurityCheckWord] != null)
        //{
        //    salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
        //}
        //else
        //{
        //    if (Session[CE.Global.General.SecurityCheckWord] != null)
        //    {
        //        salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
        //    }
        //    else
        //    {
        //        salt = myimage.GetRandomWord("all");
        //    }
        //}

        //Session[CE.Global.General.SecurityCheckWord] = salt;

        //imgCAPTCHA.ImageUrl = @"~/CAPTCHA/CAPTCHAImageHandler.ashx?id=" + CE.Security.MySecurity.Encrypt(salt, true);
        //txtSecurityCode.Text = "";
    }

    private void SetPassword(bool bStatus)
    {
        divPassword.Visible = bStatus;
        divReEnterPassword.Visible = bStatus;
        rfvPassword.Enabled = bStatus;
        rfvReEnterPassword.Enabled = bStatus;

        txtEmailAddress.Enabled = bStatus;
    }

    private void GetCarPolicyDetail()
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarPolicy _carpolicy = new CarPolicy();

        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        CarPolicyDB _carpolicydb = new CarPolicyDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Int64 _refceuserid = 0;
        Int64 _carid = 0;

        if (Session[General.UserId] != null)
        {
            _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
        }

        if (Session[General.CarId] != null)
        {
            _carid = Convert.ToInt64(Session[General.CarId].ToString());
            _cardetail = _cardetaildb.GetCar(_carid, _refceuserid);
        }

        _carpolicy = _carpolicydb.GetCarPolicy(_carid, _refceuserid);

        if (_cardetail != null && _carpolicy != null)
        {
            //lblTypeofinsurance.Text = _carpolicy.InsuranceType.ToString().Substring(0, 1);
            //lblTypeofRepair.Text = _carpolicy.GarageType == 1 ? "Authorized" : "Dealer";
            if (_carpolicy.GarageType == 1)
            {
                //lblTypeofRepair.Text = Resources.CarInsurance.Garage_Authorized;
            }
            else
            {
                //lblTypeofRepair.Text = Resources.CarInsurance.Garage_Dealer;
            }
            //lblSumInsured.Text = string.Format("{0:#,0}", _carpolicy.SumInsured) + " " + Resources .CarInsurance.Baht;
            //lblPurchase.Text = _carpolicy.IsCTPL ? "Yes" : "No";
            //lblCurrentInsurer.Text = _carpolicy.CurrentInsurer.ToString();

            //lblCarBrand.Text = _cardetail.CarMakeName.ToString();
            string MainString = _cardetail.MakeModelDesc.ToString();
            string[] Split = MainString.Split(new Char[] { ' ' });
            //lblCarBrand.Text = Split[0];

            //lblCarModel.Text = _cardetail.CarModelName.ToString();
            //lblCarYear.Text = _cardetail.ManufactYear.ToString();
            //lblCarRegistration.Text = _carpolicy.IsRedPlate ? "Red" : "Black-White";
            //lblTypeofVehicle.Text = _carpolicy.VehicleType == 110 ? "Private use" : "Commerical use";
            if (_carpolicy.VehicleType == 110) //? "Private use" : "Commerical use";
            {
                //lblTypeofVehicle.Text = Resources.CarInsurance.VehicleType_Private;
            }
            else
            {
                //lblTypeofVehicle.Text = Resources.CarInsurance.VehicleType_Commercial;
            }

        }

        _profile = null;
        _profiledb = null;
        _cardetail = null;
        _cardetaildb = null;
        _carpolicy = null;
        _carpolicydb = null;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            if (_useraccountdb.IsAlreadyExist(txtEmailAddress.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer)))
            {
                //divNewErrorMessage.Visible = true;
                //lblCarInsProfileMessage.Text = "Email address is already registered!";
                txtEmailAddress.ControlStyle.CssClass = "validationError";
                _retVal = 0;
            }
            else
            {
                Profile _userprofile = new Profile();
                ProfileDB _userprofiledb = new ProfileDB();
                Contact _contact = new Contact();
                ContactDB _contactdb = new ContactDB();

                long _result = -1;
                //divNewErrorMessage.Visible = false;
                //lblCarInsProfileMessage.Visible = false;

                _useraccount.Email = txtEmailAddress.Text.ToLower();

                //Random _random = new Random();
                string _authcode = txtMobileNo.GetPhoneNo();
                //Sakthi on 21 Jan 2011
                //_authcode = "C" + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();
                //_authcode = _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();

                _useraccount.AuthCode = _authcode;

                _useraccount.UserId = "CEUSERAUTOIDCI";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;

                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;

                if (_result > 0)
                {
                    _userprofile.Salutation = ""; //ddlSalutation.GetSalutation();
                    _userprofile.FirstName = Server.HtmlEncode(txtFirstName.Text);
                    _userprofile.SurName = Server.HtmlEncode(txtSurName.Text);

                    DateTime _dtDOB = new DateTime(1900, 1, 1);
                    _userprofile.DOB = _dtDOB;

                    _userprofile.DOB = usrDOB.GetDate();
                    _userprofile.Gender = Convert.ToChar(ddlGender.GetGender());

                    //_userprofile.MaritalStatus = Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
                    //_userprofile.JobNature = ddlJobNature.GetJobNature();
                    _userprofile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());
                    //_userprofile.YearDriveSg = Convert.ToInt16(ddlYearDriveSg.Text);
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtMobileNo.GetPhoneNo();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        SaveUserLoginInformation(_useraccount.CEID, _useraccount.UserTypeId);
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                        //SendMailToUser(_useraccount.Email, Session[CE.Global.General.UserName].ToString(), _contact.Mobile);
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    #region login existing user

    protected void imgbtnLogin_Click(object sender, EventArgs e)
    {
        if (AutoLogin(100))
        {
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());

            }

            Int64 _carId = 0;

            if (Session[General.CarId] != null)
            {
                _carId = Convert.ToInt64(Session[General.CarId].ToString());
            }
            else
            {
                //Response.Redirect("carandpolicy_details.aspx");
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/your-details.aspx", Page);
                Response.Redirect(_redirectUrl);
            }

            if (_userId > 0)
            {
                inputLoginHide.Value = "1";

                //update RefIds
                CarDetailTHDB cardb = new CarDetailTHDB();
                cardb.UpdateCarDetailPolicy(_carId, _userId);

                //btnNext.Enabled = true;
                //divPassword.Visible = false;
                vsCarProfile.Visible = false;
                //divNewErrorMessage.Visible = false;

                mpePassword.Hide();
                divExisting.Visible = false;
                //ShowCustomerDetail(_userId);

                inputLoginCount.Value = "0";

                //this.Page_Load(this, null);
                //Response.Redirect("profile.aspx");

            }

        }
        else
        {

            Int32 logincount = Convert.ToInt32(inputLoginCount.Value.Trim());
            inputLoginCount.Value = (logincount + 1).ToString();

            if (logincount == 2)
            {
                inputHideSignal.Value = "1";
            }
            else if (logincount >= 3)
            {
                this.btnPasswordClose_Click(this, null);
            }
            else
            {
                mpePassword.Show();
            }
        }

    }

    protected void btnPasswordClose_Click(object sender, EventArgs e)
    {
        inputLoginCount.Value = "0";

        _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/your-details.aspx", Page);
        Response.Redirect(_redirectUrl);
    }

    private bool AutoLogin(int LoginType)
    {
        bool isLoggedin = false;
        AccountStatus _accountstatus = new AccountStatus();
        AccountStatusDB _accountstatusdb = new AccountStatusDB();
        AccountDB _accountdb = new AccountDB();
        //Check Customer Account

        Account _account = _accountdb.GetUserAccount(txtExEmail.Text.ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));

        if (_account != null)
        {
            if (CheckUserLoginCached(_account.CEID.ToString()))
            {
                _accountstatus = _accountstatusdb.GetAccountStatus(_account.CEID, 400);

                if (Server.HtmlDecode(txtExAuthCode.Text) == _account.AuthCode)
                {
                    if (_account.Status == true)
                    {
                        isLoggedin = true;

                        if (_account.Info1 == "0")
                        {
                            //Reset Email Fail Message
                            _account.Info1 = "";
                            _account.Info2 = "";
                            _accountdb.Insert(_account);
                        }

                        _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 1);
                        lblEmailMessage.Visible = false;
                        GetUserInformation(_account);
                        SaveUserLoginInformation(_account.CEID, _account.UserTypeId);
                        CE.Global.General.CreateUpdateUserLoginCached(Page);
                        _account = null;
                        //if (LoginType == 100)
                        //{
                        //    //Response.Redirect("profile.aspx");
                        //    Response.Redirect("carAndpolicy_details.aspx");
                        //}
                        //else
                        //{
                        //    if (Session[CE.Global.General.UserProfileAndContactComplete].ToString() == "1")
                        //        Response.Redirect("~/User/ViewResultHistory.aspx?resulttitle=100");
                        //    else
                        //    {
                        //        Response.Redirect("~/User/EditProfile.aspx");
                        //    }
                        //}
                    }
                    else
                    {
                        lblEmailMessage.Visible = true;
                        lblEmailMessage.Text = "Your email has been blocked!";
                    }
                }
                else
                {
                    _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 0);
                    lblEmailMessage.Visible = true;
                    lblEmailMessage.Text = Resources.Menu.EmailPasswordIncorrect;//"Email address or password is incorrect.";
                }
            }
            else
            {
                //Response.Redirect("UserMessage.aspx?ErrorCode=1993");
                //Response.Redirect("~/user/usermessage.aspx?mt=UM&ec=1993");
                _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                Session["UMMSG"] = "UM,1993";
                Response.Redirect(_redirectUrl);
            }
        }
        else
        {
            lblEmailMessage.Visible = true;
            lblEmailMessage.Text = Resources.Menu.EmailPasswordIncorrect;
        }

        return isLoggedin;
    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = General.GetUTCDateTime();
        _loghis.EndTime = General.GetUTCDateTime();
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;

            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;

            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;

            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;

            //_loginfo.Info1 = Request.Browser.Tables;
            //_loginfo.Info2 = Request.Browser.Platform;
            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }

    private void GetUserInformation(Account _account)
    {
        DateTime dtNow = new DateTime();
        dtNow = General.GetUTCDateTime();
        Session[CE.Global.General.UserId] = _account.CEID;
        Session[CE.Global.General.UserTypeId] = _account.UserTypeId;

        if (_account.UserTypeId == Convert.ToInt32(CE.Global.CEUserType.Provider))
        {
            CE.Provider.ProviderCompanyLink _comlink = new CE.Provider.ProviderCompanyLink();
            CE.Provider.ProviderCompanyLinkDB _comlinkdb = new CE.Provider.ProviderCompanyLinkDB();
            _comlink = _comlinkdb.GetProviderCompanyId(_account.CEID);
            if (_comlink != null)
            {
                Session[CE.Global.General.ProviderCompanyId] = _comlink.ProviderCompanyId;
            }
        }

        Session[CE.Global.General.UserEmail] = _account.Email;
        Session[CE.Global.General.StartTime] = dtNow.ToString();
        bool isProfileComplete = false;
        bool isContactComplete = false;

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _contact = _contactdb.GetContact(_account.CEID);

        _profile = _profiledb.GetProfile(_account.CEID);

        if (_contact != null)
        {
            isContactComplete = true;
            Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
        }
        else
        {
            Session[CE.Global.General.UserPhoneNo] = null;
        }

        if (_profile != null)
        {
            if (_profile.FirstName != null && _profile.FirstName != string.Empty)
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName) + " " + Server.HtmlDecode(_profile.FirstName);
            }
            else
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName);
            }

            if (!string.IsNullOrEmpty(_profile.IDType) &&
                !string.IsNullOrEmpty(_profile.IDNo) &&
                _profile.IDNo.Length == 9)
            {
                Session[CE.Global.General.UserICNumber] = _profile.IDType + " " + _profile.IDNo;
            }

            if (_profile.Status.ToLower() == "complete")
            {
                isProfileComplete = true;
            }
            else
            {
                isProfileComplete = false;
            }
        }
        else
        {
            Session[CE.Global.General.UserName] = null;
        }

        if (isProfileComplete && isContactComplete)
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "1";
        }
        else
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "0";
        }

    }

    private bool CheckUserLoginCached(string UserId)
    {
        bool _retValue = false;
        string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.UserCacheName");
        sKey += UserId;
        if (HttpContext.Current.Cache[sKey] == null)
        {
            _retValue = true;
        }
        else
        {
            _retValue = false;
        }
        return _retValue;
    }
    #region remove   
    //private void RegisterUser()
    //{
    //    Account _useraccount = new Account();
    //    AccountDB _useraccountdb = new AccountDB();

    //    Profile _userprofile = new Profile();
    //    ProfileDB _userprofiledb = new ProfileDB();
    //    Contact _contact = new Contact();
    //    ContactDB _contactdb = new ContactDB();

    //    long _result = -1;

    //    _useraccount.Email = txtEmailAddress.Text.ToLower();

    //    Random _random = new Random();
    //    string _authcode = "";
    //    //Sakthi on 21 Jan 2011
    //    //_authcode = "C" + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();
    //    _authcode = _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();

    //    _useraccount.AuthCode = _authcode;

    //    _useraccount.UserId = "CEUSERAUTOIDCI";
    //    _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
    //    _useraccount.IsAcceptTC = true;
    //    _useraccount.Status = true;
    //    if (Session[General.AgentId] != null)
    //    {
    //        //For Agent Create User - Phyo @28/Apr/2011
    //        _useraccount.RefCEUserID = Convert.ToInt64(Session[General.AgentId]);
    //    }
    //    else
    //    {
    //        _useraccount.RefCEUserID = -1;
    //    }
    //    _result = _useraccountdb.Insert(_useraccount);
    //    _useraccount.CEID = _result;

    //    if (_result > 0)
    //    {
    //        //_userprofile.Salutation = ddlSalutation.GetSalutation();

    //        _userprofile.FirstName = Server.HtmlEncode(txtFirstName.Text.ToUpper());
    //        _userprofile.SurName = Server.HtmlEncode(txtSurName.Text.ToUpper());

    //        DateTime _dtDOB = new DateTime(1900, 1, 1);
    //        _userprofile.DOB = _dtDOB;

    //        _userprofile.DOB = usrDOB.GetDate();
    //        _userprofile.Gender = Convert.ToChar(ddlGender.GetGender());

    //        //_userprofile.MaritalStatus = Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
    //        //_userprofile.JobNature = ddlJobNature.GetJobNature();
    //        _userprofile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());
    //        //_userprofile.YearDriveSg = Convert.ToInt16(ddlYearDriveSg.Text);
    //        _userprofile.Status = "Complete";
    //        _userprofile.RefCEUserId = _useraccount.CEID;
    //        _result = _userprofiledb.Insert(_userprofile);

    //        _contact.Email = _useraccount.Email;
    //        _contact.Mobile = txtMobileNo.GetPhoneNo();

    //        _contact.Status = true;
    //        _contact.RefCEUserId = _useraccount.CEID;
    //        _result = _contactdb.Insert(_contact);

    //        if (_result > 0)
    //        {
    //            SaveUserLoginInformation(_useraccount.CEID, _useraccount.UserTypeId);
    //            Session[CE.Global.General.UserId] = _useraccount.CEID;
    //            Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
    //            Session[CE.Global.General.UserEmail] = _useraccount.Email;
    //            Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
    //            Session[CE.Global.General.StartTime] = DateTime.Now.ToString();
    //            if (_userprofile.FirstName != string.Empty)
    //            {
    //                Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
    //            }
    //            else
    //            {
    //                Session[CE.Global.General.UserName] = _userprofile.SurName;
    //            }

    //            //update CarIds/userids
    //            Int64 _userId = Convert.ToInt64(Session[General.UserId].ToString());
    //            Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());

    //            CarDetailTHDB cardb = new CarDetailTHDB();
    //            cardb.UpdateCarDetailPolicy(_carId, _userId);

    //            Session[CE.Global.General.UserProfileAndContactComplete] = "1";
    //            string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive");
    //            if (_strCXLive != "")
    //            {
    //                //if (!SendMailToUser(_useraccount.Email,"",_authcode))
    //                if (!SendMailToUser(txtEmailAddress.Text.Trim(), Session[CE.Global.General.UserName].ToString(), txtMobileNo.GetPhoneNo()))
    //                {
    //                    //Email Can't be sent
    //                    _useraccount.Info1 = "0";
    //                    _useraccount.Info2 = "New User - Car Insurance";
    //                    _result = _useraccountdb.Insert(_useraccount);

    //                }
    //            }
    //            //Response.Redirect("results-new.aspx?sortby=" + ddlSortBy.Text);
    //            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/quote-results.aspx", Page);
    //            Response.Redirect(_redirectUrl);
    //        }
    //    }
    //}
    #endregion

    #endregion

    protected void txtEmailAddress_TextChanged(object sender, EventArgs e)
    {
        if (divConfirmEmail.Visible == false)
        {
            divConfirmEmail.Visible = true;
            txtConfirmEmailAddress.Focus();
        }
    }
}
